LWIP_DIR := $(dir $(abspath $(lastword $(MAKEFILE_LIST))))
ROOT_DIR := $(dir $(abspath $(LWIP_DIR)))

LWIP_INC = $(LWIP_DIR)/include
DPDK_INCLUDE_FILE ?= /usr/include/dpdk

SEC_FLAGS = -fstack-protector-strong -Werror -Wall -Wl,-z,relro,-z,now -Wl,-z,noexecstack -Wtrampolines -fPIC -D_FORTIRY_SOURCE=2

CC = gcc
AR = ar
OPTIMIZATION = -O3
INC = -I$(LWIP_DIR) \
      -I$(LWIP_INC) \
      -I$(DPDK_INCLUDE_FILE)

CFLAGS = -g $(OPTIMIZATION) $(INC) $(SEC_FLAGS)
ARFLAGS = crDP

ifeq ($(shell $(CC) -dumpmachine | cut -d"-" -f1), x86_64)
    CFLAGS += -mssse3
endif
ifeq ($(DPDK_VERSION_1911), 1)
    CFLAGS += -DDPDK_VERSION_1911=1
endif

SRCS =
DIRS = api core netif

define register_dir
SRCS += $(patsubst %, $(1)/%, $(2))
endef

include $(patsubst %, %/dir.mk, $(DIRS))

OBJS = $(subst .c,.o,$(SRCS))
TMPS := $(subst .c,.s,$(SRCS))
TMPS += $(subst .c,.i,$(SRCS))

LWIP_LIB = liblwip.a

INSTALL_LIB = $(DESTDIR)/usr/lib64
INSTALL_INC = $(DESTDIR)/usr/include/lwip

.PHONY: all
all: $(LWIP_LIB)

.depend: $(SRCS)
	rm -f ./.depend
	$(foreach SRC,$(SRCS),$(CC) $(CFLAGS) -MM -MT $(SRC:.c=.o) $(SRC) >> .depend;)

-include .depend

$(LWIP_LIB): $(OBJS)
	$(AR) $(ARFLAGS) $@ $(OBJS)

.PHONY: install
install:
	install -dp $(INSTALL_LIB) $(INSTALL_INC)
	install -Dp $(LWIP_DIR)/$(LWIP_LIB) $(INSTALL_LIB)
	cp -pr $(LWIP_INC)/* $(INSTALL_INC)/

.PHONY: clean
clean:
	$(RM) $(LWIP_LIB) $(OBJS) $(TMPS) .depend
